<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '选择绘本集',
  },
}
</route>

<script lang="ts" setup>
import type { BookSetRespVO } from '@/api/types/book'
import { computed, onMounted, ref } from 'vue'
import { getBookSetPage, searchBookSets } from '@/api/book'

// 页面状态
const statusBarHeight = ref(0)
const searchKeyword = ref('')
const selectedIds = ref<number[]>([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(20)

// 绘本集数据
const bookSets = ref<BookSetRespVO[]>([])
const searchResults = ref<BookSetRespVO[]>([])
const isSearching = ref(false)
// 缓存所有已选择的绘本集详细信息，确保数据不丢失
const selectedBookSetsCache = ref<Map<number, BookSetRespVO>>(new Map())

// 搜索防抖
let searchTimer: number | null = null

// 更新选中绘本集的缓存
function updateSelectedCache() {
  // 从当前加载的绘本集中找到已选择的项目并添加到缓存
  const currentList = isSearching.value ? searchResults.value : bookSets.value
  selectedIds.value.forEach((id) => {
    if (!selectedBookSetsCache.value.has(id)) {
      const bookSet = currentList.find(set => set.id === id)
      if (bookSet) {
        selectedBookSetsCache.value.set(id, bookSet)
      }
    }
  })
}

// 显示的绘本集列表
const filteredBookSets = computed(() => {
  return isSearching.value ? searchResults.value : bookSets.value
})

// 加载绘本集数据
async function loadBookSets(page = 1, isRefresh = false) {
  if (loading.value)
    return

  try {
    loading.value = true

    const params = {
      pageNo: page,
      pageSize: pageSize.value,
      isActive: true,
    }

    const response = await getBookSetPage(params)

    if (response && response.code === 0) {
      const { list, total } = response.data

      if (isRefresh) {
        bookSets.value = list
      }
      else {
        bookSets.value = [...bookSets.value, ...list]
      }

      currentPage.value = page
      hasMore.value = bookSets.value.length < total

      // 更新缓存中已选择的绘本集
      updateSelectedCache()
    }
    else {
      uni.showToast({
        title: response?.msg || '加载失败',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('加载绘本集失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 搜索绘本集
async function searchBookSetsByKeyword() {
  if (!searchKeyword.value.trim()) {
    isSearching.value = false
    return
  }

  try {
    loading.value = true
    isSearching.value = true

    console.log('开始搜索绘本集，关键词:', searchKeyword.value)

    const response = await searchBookSets({
      keyword: searchKeyword.value,
      pageNo: 1,
      pageSize: 50,
    })

    console.log('搜索响应:', response)

    if (response && response.code === 0) {
      searchResults.value = response.data?.list || []
      console.log('搜索结果数量:', searchResults.value.length)

      // 更新缓存中已选择的绘本集
      updateSelectedCache()
    }
    else {
      console.error('搜索失败:', response?.msg)
      uni.showToast({
        title: response?.msg || '搜索失败',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('搜索绘本集失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0

  // 获取已选择的绘本集ID
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.options || {}

  if (options.selected) {
    try {
      selectedIds.value = JSON.parse(options.selected)
    }
    catch (error) {
      console.log('解析已选择绘本集失败:', error)
    }
  }

  // 加载绘本集数据
  loadBookSets(1, true)
})

// 加载更多
function loadMore() {
  if (!loading.value && hasMore.value) {
    loadBookSets(currentPage.value + 1, false)
  }
}

// 搜索（带防抖）
function onSearch() {
  // 清除之前的定时器
  if (searchTimer !== null) {
    clearTimeout(searchTimer)
  }

  // 设置新的定时器，延迟500ms执行搜索
  searchTimer = setTimeout(() => {
    if (searchKeyword.value.trim()) {
      searchBookSetsByKeyword()
    }
    else {
      isSearching.value = false
    }
    searchTimer = null
  }, 500)
}

// 切换选择状态
function toggleSelection(id: number) {
  const index = selectedIds.value.indexOf(id)
  if (index > -1) {
    // 取消选择
    selectedIds.value.splice(index, 1)
    selectedBookSetsCache.value.delete(id)
  }
  else {
    // 添加选择
    selectedIds.value.push(id)

    // 缓存绘本集信息
    const currentList = isSearching.value ? searchResults.value : bookSets.value
    const bookSet = currentList.find(set => set.id === id)
    if (bookSet) {
      selectedBookSetsCache.value.set(id, bookSet)
    }
  }
}

// 确认选择
function confirmSelection() {
  // 优先从缓存中获取选中的绘本集
  const selectedBookSets: BookSetRespVO[] = []

  for (const id of selectedIds.value) {
    // 首先尝试从缓存中获取
    let bookSet = selectedBookSetsCache.value.get(id)

    // 如果缓存中没有，再从当前列表中查找
    if (!bookSet) {
      bookSet = bookSets.value.find(set => set.id === id)
        || searchResults.value.find(set => set.id === id)

      // 如果找到了，添加到缓存中
      if (bookSet) {
        selectedBookSetsCache.value.set(id, bookSet)
      }
    }

    if (bookSet) {
      selectedBookSets.push(bookSet)
    }
    else {
      console.warn(`未找到ID为${id}的绘本集`)
    }
  }

  console.log('已选择绘本集:', selectedBookSets)
  console.log('选中的ID:', selectedIds.value)
  console.log('缓存的绘本集数量:', selectedBookSetsCache.value.size)

  // 通过事件传递选择的绘本集
  uni.$emit('bookSetsSelected', selectedBookSets)

  // 返回上一页
  uni.navigateBack()
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}
</script>

<template>
  <view class="select-book-sets">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: `${statusBarHeight}px` }">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <uni-icons type="left" size="20" color="#333" />
          <text class="back-text">
            返回
          </text>
        </view>
        <view class="navbar-title">
          <text class="title-text">
            选择绘本集
          </text>
        </view>
        <view class="navbar-right">
          <text class="confirm-btn" @click="confirmSelection">
            确定({{ selectedIds.length }})
          </text>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box">
        <text class="search-icon">
          🔍
        </text>
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索绘本集"
          @input="onSearch"
        >
      </view>
    </view>

    <!-- 绘本集列表 -->
    <view class="book-sets-list">
      <view
        v-for="bookSet in filteredBookSets"
        :key="bookSet.id"
        class="book-set-item"
        :class="{ selected: selectedIds.includes(bookSet.id) }"
        @click="toggleSelection(bookSet.id)"
      >
        <view class="set-cover-container">
          <image class="set-cover" :src="bookSet.cover" mode="aspectFill" />
          <view class="book-count-badge">
            {{ bookSet.bookCount }}本
          </view>
        </view>
        <view class="set-info">
          <text class="set-title">
            {{ bookSet.title }}
          </text>
          <text class="set-description">
            {{ bookSet.description }}
          </text>
          <view class="set-tags">
            <text class="tag">
              {{ bookSet.categoryName || bookSet.source || '绘本集' }}
            </text>
            <text class="tag">
              {{ bookSet.ageRange }}
            </text>
          </view>
        </view>
        <view class="selection-indicator">
          <view class="checkbox" :class="{ checked: selectedIds.includes(bookSet.id) }">
            <text v-if="selectedIds.includes(bookSet.id)" class="check-icon">
              ✓
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && filteredBookSets.length === 0" class="loading-state">
      <text class="loading-text">
        加载中...
      </text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && filteredBookSets.length === 0" class="empty-state">
      <text class="empty-text">
        没有找到相关绘本集
      </text>
    </view>

    <!-- 加载更多 -->
    <view v-if="!isSearching && hasMore" class="load-more" @click="loadMore">
      <text class="load-more-text">
        {{ loading ? '加载中...' : '加载更多' }}
      </text>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.select-book-sets {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 自定义导航栏 */
.custom-navbar {
  // padding-top: 20px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .navbar-content {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
    padding-top: 30px;

    .navbar-left {
      display: flex;
      align-items: center;

      .back-icon {
        font-size: 20px;
        color: #333;
        margin-right: 5px;
      }

      .back-text {
        font-size: 16px;
        color: #333;
      }
    }

    .navbar-title {
      flex: 1;
      text-align: center;

      .title-text {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
    }

    .navbar-right {
      .confirm-btn {
        font-size: 16px;
        color: #007aff;
        font-weight: 500;
      }
    }
  }
}

/* 搜索栏 */
.search-section {
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .search-box {
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 20px;
    padding: 8px 15px;

    .search-icon {
      margin-right: 8px;
      font-size: 16px;
    }

    .search-input {
      flex: 1;
      font-size: 16px;
      background-color: transparent;
    }
  }
}

/* 绘本集列表 */
.book-sets-list {
  padding: 15px;
}

.book-set-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 10px;
  // transition: all 0.2s ease;

  &.selected {
    border: 2px solid #007aff;
    background-color: #f0f8ff;
    padding: 13px;
  }

  .set-cover-container {
    position: relative;
    margin-right: 15px;

    .set-cover {
      width: 60px;
      height: 80px;
      border-radius: 6px;
    }

    .book-count-badge {
      position: absolute;
      top: 5px;
      right: 5px;
      background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
      color: #1e293b;
      font-size: 10px;
      font-weight: 600;
      padding: 2px 6px;
      border-radius: 8px;
      min-width: 16px;
      text-align: center;
      box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
      border: 1px solid rgba(255, 255, 255, 0.8);
    }
  }

  .set-info {
    flex: 1;

    .set-title {
      display: block;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .set-description {
      display: block;
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .set-tags {
      display: flex;
      gap: 6px;

      .tag {
        background-color: #e8f4fd;
        color: #007aff;
        font-size: 12px;
        padding: 2px 8px;
        border-radius: 10px;
      }
    }
  }

  .selection-indicator {
    margin-left: 15px;

    .checkbox {
      width: 24px;
      height: 24px;
      border: 2px solid #ddd;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;

      &.checked {
        background-color: #007aff;
        border-color: #007aff;
      }

      .check-icon {
        color: #fff;
        font-size: 14px;
        font-weight: bold;
      }
    }
  }
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;

  .loading-text {
    font-size: 16px;
    color: #666;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;

  .empty-text {
    font-size: 16px;
    color: #999;
  }
}

/* 加载更多 */
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  margin: 20px 15px;
  background-color: #fff;
  border-radius: 12px;

  .load-more-text {
    font-size: 16px;
    color: #007aff;
  }
}
</style>
